package web.controller;

import common.Const;
import entity.Users;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * User: key
 * ClassName:UserController
 * Date: 2023/5/6
 * Time: 15:09
 * description:
 */
@WebServlet("/user")
public class UserController extends HttpServlet {
    private UserService us = new UserServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method == null){
            method = "error";
        }
        switch (method){
            case "login":
                login(req, resp);
                break;
            case "logout":
                logout(req,resp);
                break;
            case "reg":
                try {
                    reg(req,resp);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "error":
            default:
                req.setAttribute(Const.MSG,"不好意思，你访问的网页不存在或者没找到");
                req.getRequestDispatcher("message.jsp").forward(req,resp);
        }
    }

    private void reg(HttpServletRequest req, HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Users u = new Users();
        BeanUtils.populate(u,parameterMap);
        boolean flag = us.reg(u);
        String msg = "注册失败";
        if(flag){
            msg = "注册成功";
        }
        req.setAttribute(Const.MSG,msg);
        req.getRequestDispatcher("message.jsp").forward(req,resp);
    }

    //注销账户
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect("/login.jsp");
    }

    //登陆验证
    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String userCode = req.getParameter("userCode");
        String password = req.getParameter("password");
        Users user = us.doLogin(userCode,password);
        if (user != null) {
            req.getSession().setAttribute(Const.LOGIN_INFO,user);
            resp.sendRedirect("/book?method=getByPage&pageNum=1");
        }else {
            req.setAttribute(Const.MSG,"登陆失败,用户名或密码有误");
            req.getRequestDispatcher("message.jsp").forward(req, resp);
        }
    }
}
